<?php

namespace app\common\model;

use app\common\model\BaseModel;
use Exception;
use think\Session;
use \phpseclib\Crypt\RSA;

/**
 * 用户模型
 * Class User
 * @package app\common\model
 */
class Member extends BaseModel
{
    protected $name = 'member';

    // 定义一个方法用于减去指定数值
    public function subtractScore($user_name, $value)
    {
        // 使用where方法根据用户ID进行筛选
        $user = $this->where('user_name', $user_name)->find();

        // 检查用户是否存在
        if ($user) {
            // 减去指定数值
            $user->balance -= $value;
            if ($user->balance < 0) {
                return false;
            }
            // 保存修改后的数据到数据库
            $user->save();

            return true; // 返回操作成功的信息
        } else {
            return false; // 返回操作失败的信息
        }
    }

    //加上指定值
    public function plusstractScore($user_name, $value)
    {
        // 使用where方法根据用户ID进行筛选
        $user = $this->where('user_name', $user_name)->find();

        // 检查用户是否存在
        if ($user) {
            // 减去指定数值
            $user->balance += $value;

            // 保存修改后的数据到数据库
            $user->save();

            return true; // 返回操作成功的信息
        } else {
            return false; // 返回操作失败的信息
        }
    }

    /**
     * 用户注册
     */
    public function register($arr)
    {
        $user = $this->where(['user_name' => $arr['userName']])->find();

        if ($user) {
            $this->error = '用户已存在';
            //用户已存在
            return false;
        }
        //判断如果是通过他人邀请注册的则生成对应的记录
        if (isset($arr['invitation_code']) && $arr['invitation_code'] != '') {
            //先判断邀请码是否存在，如果不存在则返回
            if (!db('member')->where('invitation_code', $arr['invitation_code'])->count()) {
                $this->error = '邀请码不存在';
                //邀请码不存在
                return false;
            }
            $inviteList = new InviteList();
            $inviteList->save(['invitation_code' => $arr['invitation_code'], 'user_name' => $arr['userName']]);
        }
        //生成自己的邀请码
        $randomStr = GetRandStr(6);
        //生成唯一uid
        $oldUids = db('member')->field('uid')->select();
        $uid = generateUniqueRandomNumber();
        $repeat = true;
        while ($repeat) {
            foreach ($oldUids as $key => $value) {
                if ($value['uid'] == '') {
                    $repeat = false;
                    continue;
                }
                if ($value['uid'] != '' && $value['uid'] == $uid) {
                    $uid = generateUniqueRandomNumber();
                    $repeat = true;
                    break;
                }
                $repeat = false;
            }
        }
        try {
            $data = [
                'user_name' => $arr['userName'],
                'password' => yoshop_hash($arr['passwd']),
                'avatar_url' => 'assets/member/images/avatar.jpg',
                'nick_name' => $arr['nickName'],
                'type' => isset($arr['type']) ?: 0,
                'mobile' => $arr['mobile'],
                'uid'  => $uid,
                'invitation_code' => $randomStr,
            ];
            $this->save($data);
            return true;
        } catch (Exception $e) {
            $this->error = '注册失败';
            return false;
        }
    }

    /**
     * 用户登录
     */
    public function login($arr)
    {
        $user = $this->where(['user_name' => $arr['userName'], 'password' => yoshop_hash($arr['passwd'])])->find();
        if (!$user) {
            return false;
        }

        try {

            $info = [
                'user_name' => $user['user_name'],
                'avatar_url' => $user['avatar_url'],
                'nick_name' => $user['nick_name'],
                'mobile' => $user['mobile'],
                'uid' => $user['uid'],
                'invitation_code' => $user['invitation_code']

            ];
            session($arr['userName'], $info);
            //修改在线状态
            $user->online = 1;
            $user->save();

            return $info;
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * 关联微信小程序表
     * @return \think\model\relation\BelongsTo
     */
    public function wxapp()
    {
        $module = self::getCalledModule() ?: 'common';
        return $this->belongsTo("app\\{$module}\\model\\Wxapp");
    }

    /**
     * 关联用户角色表表
     * @return \think\model\relation\BelongsToMany
     */
    public function role()
    {
        return $this->belongsToMany('Role', 'StoreUserRole');
    }

    /**
     * 验证用户名是否重复
     * @param $user_name
     * @return bool
     */
    public static function checkExist($user_name)
    {
        return !!static::useGlobalScope(false)
            ->where('user_name', '=', $user_name)
            ->value('store_user_id');
    }

    // /**
    //  * 商家用户详情
    //  * @param $where
    //  * @param array $with
    //  * @return static|null
    //  * @throws \think\exception\DbException
    //  */
    // public static function detail($where, $with = [])
    // {
    //     !is_array($where) && $where = ['store_user_id' => (int)$where];
    //     return static::get(array_merge(['is_delete' => 0], $where), $with);
    // }

    /**
     * 保存登录状态
     * @param $user
     * @throws \think\Exception
     */
    public function loginState($user)
    {
        /** @var \app\common\model\Wxapp $wxapp */
        // $wxapp = $user['wxapp'];
        // 保存登录状态
        // Session::set('yoshop_store', [
        Session::set('cms_member', [
            'user' => [
                'id' => $user['id'],
                'corporation' => $user['corporation'],
                'enterprise_name' => $user['enterprise_name'],
                'credit_code' => $user['credit_code'],
                'address' => $user['address'],
                'mobile' => $user['mobile'],
                'avatar_url' => $user['avatar_url'],
                'rank' => $user['rank'],

            ],
            'is_login' => true,
            //  'wxapp' => $wxapp->toArray(),

        ]);
    }
}
